package com.lxl.jwt1.controller;

import com.lxl.jwt1.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@RestController
public class LoginController {


    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    PasswordEncoder passwordEncoder;

    private List<String> authorizations = new ArrayList<>();


    @PostMapping("/login")
    public Map login(String username,String pass){

        Map map = new HashMap();

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        //生成token  返回


        UserDetails userDetails = null;
        try {
            userDetails = userDetailsService.loadUserByUsername(username);
        } catch (UsernameNotFoundException e) {
            map.put("mess","账号不存在");
            return map;
        }

        if(!passwordEncoder.matches(pass,userDetails.getPassword())){
            map.put("mess","密码错误");
            return map;
        }
        //要放到security里面去
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,pass,userDetails.getAuthorities() );
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        map.put("mess","登录成功");

        stringObjectHashMap.put("username",userDetails.getUsername());
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            authorizations.add(authority.getAuthority());
        }


        stringObjectHashMap.put("menus",authorizations);

        String token = JwtUtils.getToken(username,stringObjectHashMap);
        map.put("token",token);
        return map;

    }
}